You can check if the browser supports Web Workers by checking if the Worker
object is available in the window
object.
Worker
object exists, it means the browser supports Web Workers.undefined
, the browser does not support Web Workers.A Web Worker allows you to run JavaScript in the background without blocking the main thread (UI).
worker.js
:
Explanation:
postMessage()
sends data to the worker.onmessage
receives the result from the worker.Web Workers cannot access or modify the DOM directly. This is because they run in a separate thread, isolated from the main thread where the DOM is manipulated.
❌ Not Allowed: Attempting to modify the DOM from a Web Worker:
✅ Correct Way: Use postMessage
to send the data to the main thread, which can then update the DOM:
Key Restrictions:
document
, window
, or parent
.alert()
).postMessage()
to communicate with the main thread).Web Workers are designed for offloading heavy computations to keep the main thread responsive.